package hlhj.com.carviewpad.customview

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.os.Environment
import android.widget.Toast
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.FileCallback
import com.lzy.okgo.model.Progress
import com.lzy.okgo.model.Response
import hlhj.com.carviewpad.R
import hlhj.com.carviewpad.http.Urls
import hlhj.com.carviewpad.javabean.FilesBean
import kotlinx.android.synthetic.main.dialog_updata.*
import java.io.File

/**
 * Created by Never Fear   on 2019\1\15 0015.
Never More....
 */
class UpdataDialog(private val  c:Context,private val filesBean: FilesBean) :Dialog(c) {
    var i=0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_updata)
        setCancelable(false)

        if (filesBean.info.size>0){
            downLoad(filesBean)

        }
    }
    private fun downLoad(filesBean: FilesBean) {
        tvNum.text="${i+1} / ${filesBean.info.size}"
        val bean = filesBean.info[i]
        var cover="1"
        if (bean.cover.isNotEmpty()){
            cover=bean.cover
        }
        if (bean.type.equals("1")){
            OkGo.get<File>(Urls.downUrl+bean.cover)
                    .execute(object :FileCallback(Environment.getExternalStorageDirectory().absolutePath+"/carpad/cover/","cover_${bean.advertising_id}.${bean.cover.split(".")[1]}"){
                        override fun onSuccess(response: Response<File>?) {

                        }
                    })
        }
        OkGo.get<File>(Urls.downUrl + bean.url)
                .execute(object : FileCallback(Environment.getExternalStorageDirectory().absolutePath+"/carpad","_${bean.advertising_id}_${bean.advertising_name}_${bean?.type}" +
                        "_${bean.start_time}_${bean.end_time}_${bean?.area_name}_${bean?.area_id}_${bean?.duration}_.${bean?.url?.split(".")!![1]}") {
                    override fun onSuccess(response: Response<File>?) {

                    }

                    override fun downloadProgress(progress: Progress?) {
                        super.downloadProgress(progress)
                        progressBar.progress=(progress?.fraction!!*100).toInt()

                    }
                    override fun onError(response: Response<File>?) {
                        super.onError(response)
                    }

                    override fun onFinish() {
                        super.onFinish()
                        i++
                        if (i <= filesBean.info.size - 1) {
                            downLoad(filesBean)
                        }else{
                            Toast.makeText(c,"更新完成",Toast.LENGTH_SHORT).show()
                            dismiss()
                        }
                    }
                })
    }
}